package middleware

import (
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/text/gstr"
	"go-middle/app/admin/service/adminservice"
	"go-middle/app/admin/service/loginservice"
	"go-middle/app/common/model/admin"
	"go-middle/library/response"
)

//web 验证登录
func CheckLoginAdminWeb(r *ghttp.Request) {
	if r.Session.GetString("user") == "" {
		r.Response.RedirectTo("/admin/login")
	}
	checkPermissionWeb(r)
	r.Middleware.Next()
}

//api 验证登录
func CheckLoginAdminApi(r *ghttp.Request) {
	if r.Session.GetString("user") == "" {
		response.StatusCode(r, 401, "请先登录")
	}
	checkPermissionApi(r)
	r.Middleware.Next()
}

//web 验证权限
func checkPermissionWeb(r *ghttp.Request) {
	ignore := []string{"/admin"}
	if r.Session.GetInt64("uid") != 1 && !gstr.InArray(ignore, r.Router.Uri) {
		var user admin.Entity
		_ = r.Session.GetStruct(loginservice.AdminInfo, &user)
		if !adminservice.CheckPermission(user.Roles, r.Router.Uri, r.Router.Method) {
			_ = r.Response.WriteTpl("public/403.html")
			r.ExitAll()
		}
	}
}

//api 验证权限
func checkPermissionApi(r *ghttp.Request) {
	ignore := []string{"/api/system/menu"}
	if r.Session.GetInt64("uid") != 1 && !gstr.InArray(ignore, r.Router.Uri) {
		var user admin.Entity
		_ = r.Session.GetStruct(loginservice.AdminInfo, &user)
		if !adminservice.CheckPermission(user.Roles, r.Router.Uri, r.Router.Method) {
			response.StatusCode(r, 403, "权限不足")
		}
	}
}
